package cn.tjad.tjad2.module.form.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.fragment.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.FormDetail;
import cn.tjad.tjad2.data.bean.Id;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.data.bean.ValueId;
import cn.tjad.tjad2.data.event.SimpleEvent;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;
import cn.tjad.tjad2.module.common.widget.OperatePanel;
import cn.tjad.tjad2.module.form.entity.FormAsignRequestBean;
import cn.tjad.tjad2.module.form.entity.RecallRequestBean;
import cn.tjad.tjad2.module.form.entity.UpdateFormRequestBean;
import cn.tjad.tjad2.module.form.views.AttachmentSelectWidget;
import cn.tjad.tjad2.module.form.views.UserSelectWidget;
import cn.tjad.tjad2.module.form.adapter.FormDetailAdapter;
import cn.tjad.tjad2.module.form.views.ViewPortView;
import cn.tjad.tjad2.module.material.bean.request.AsignRequestBean;
import cn.tjad.tjad2.module.user.userselect.SelectMode;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.ProgressDialogUtils;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;

@Route(path = PageId.FORM_DETAIL)
public class FormDetailFragment extends BaseFragment {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.operate_panel)
    OperatePanel operatePanel;

    private FormDetailAdapter formDetailAdapter;
    private int formId = -1;
    private List<FormDetail.FormDetailStep> formDetailStep;
    private FormDetail formDetail;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            formId = bundle.getInt(Keys.FORM_ID, -1);
        }
    }

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.form_detail_view, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (formId == -1) {
            Tools.showToast("formId不能为空！");
            return;
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        formDetailAdapter = new FormDetailAdapter();
        recyclerView.setAdapter(formDetailAdapter);
        requestData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void requestData() {
        RetrofitManager.getInstance()
                .getApiService()
                .getFormDetail(Tools.getProjectId(), formId)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<FormDetail>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<FormDetail> t) {
                        formDetail = t.result;
                        titleView.setCenterText(t.result.name);
                        FormDetail formDetail = t.result;
                        if (formDetail.steps != null && formDetail.steps.size() > 0) {
                            formDetailStep = formDetail.steps;
                        } else if (formDetail.nextSteps != null && formDetail.nextSteps.size() > 0) {
                           formDetailStep = formDetail.nextSteps.subList(0, 1);
                        }
                        formDetailAdapter.setEditable(false);
                        formDetailAdapter.setFormStep(formDetailStep);
                        setOperatePanel(t.result.consStatus);
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                    }
                });
    }

    private void setOperatePanel(int consStatus) {
        operatePanel.removeAllViews();
        if (consStatus == 0) {
            operatePanel.addButton("编辑", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    formDetailAdapter.setEditable(true);
                    formDetailAdapter.setFormStep(formDetailStep.subList(0, 1));
                    formDetailAdapter.notifyDataSetChanged();
                    operatePanel.removeAllViews();
                    operatePanel.addButton("保存草稿", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateForm(0);
                        }
                    });
                    operatePanel.addButton("提交", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateForm(1);
                        }
                    });
                }
            });
            operatePanel.setVisibility(View.VISIBLE);
        } else if (consStatus == 1) {
            operatePanel.addButton("处理", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(Keys.FORM_ID, formId);
                    bundle.putSerializable(Keys.FORM_DETAIL_STEPS, formDetail.nextSteps);
                    RouteUtils.toFragmentActivity(getContext(), PageId.FORM_HANDLE, bundle);
                }
            });
            operatePanel.addButton("驳回", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(Keys.FORM_ID, formId);
                    RouteUtils.toFragmentActivity(getContext(), PageId.FORM_REJECT, bundle);
                }
            });
            operatePanel.addButton("撤回", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new TjDialogFragment.Builder(getContext())
                            .setTitle("提示")
                            .setMessage("确定要撤回该表单吗？")
                            .setPositiveButton("确定", new OnDialogClickListener() {
                                @Override
                                public boolean onClick(Dialog dialog, int which) {
                                    cancelForm();
                                    return true;
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show(getChildFragmentManager());
                }
            });
            operatePanel.addButton("转交", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SelectMode.setSelectMode(SelectMode.SINGGLE_CHOICE);
                    RouteUtils.toPageForResult((Activity) getContext(), PageId.USER_SELECT_2, null, 7002);
                }
            });
            operatePanel.setVisibility(View.VISIBLE);
        } else {
            operatePanel.setVisibility(View.GONE);
        }
    }

    private void updateForm(int consStatus) {
        if (formDetailStep == null) {
            Tools.showToast("数据异常，操作失败");
            return;
        }
        ProgressDialogUtils.show(getContext());
        UpdateFormRequestBean requestBean = new UpdateFormRequestBean();
        FormDetail.FormDetailStep editStep = formDetailStep.get(0);
        if (editStep.id > 0) {
            requestBean.id = editStep.id;
        }
        requestBean.consStatus = consStatus;
        if (editStep.step != null) {
            requestBean.step = new Id(editStep.step.id);
        }
        List<FormDetail.FormStepDetail> formStepDetails = editStep.details;
        requestBean.details = new ArrayList<>();
        if (formStepDetails != null && formStepDetails.size() > 0) {
            for (FormDetail.FormStepDetail detail: formStepDetails) {
                UpdateFormRequestBean.Detail d = new UpdateFormRequestBean.Detail();
                d.detail = new Id(detail.detail.id);
                d.value = detail.value;
                requestBean.details.add(d);
            }
        }

        RetrofitManager.getInstance().getApiService()
                .updateForm(Tools.getProjectId(), formId, requestBean)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        new AlertDialog.Builder(getContext())
                                .setCancelable(false)
                                .setTitle("提示")
                                .setMessage("操作成功！")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        EventBus.getDefault().post(new SimpleEvent(7001));
                                    }
                                }).show();
                        ProgressDialogUtils.dismiss();
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        ProgressDialogUtils.dismiss();
                    }
                });
    }

    private void cancelForm() {
        ProgressDialogUtils.show(getContext());
        RetrofitManager.getInstance().getApiService()
                .recallForm(Tools.getProjectId(), formId, new RecallRequestBean())
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        ProgressDialogUtils.dismiss();
                        new AlertDialog.Builder(getContext())
                                .setCancelable(false)
                                .setTitle("提示")
                                .setMessage("撤回表单成功！")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        EventBus.getDefault().post(new SimpleEvent(7001));
                                    }
                                }).show();
                    }

                    @Override
                    public void onFailed(String message) {
                        ProgressDialogUtils.dismiss();
                        Tools.showToast(message);
                    }
                });
    }

    private void asignFormTo(User user) {
        if (user == null) {
            Tools.showToast("转交用户不能为空");
            return;
        }
        ProgressDialogUtils.show(getContext());
        FormAsignRequestBean requestBean = new FormAsignRequestBean();
        requestBean.currentUser = new Id(user.id);
        RetrofitManager.getInstance().getApiService()
                .assignForm(Tools.getProjectId(), formId, requestBean)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        ProgressDialogUtils.dismiss();
                        new AlertDialog.Builder(getContext())
                                .setCancelable(false)
                                .setTitle("提示")
                                .setMessage("转交表单成功！")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        EventBus.getDefault().post(new SimpleEvent(7001));
                                    }
                                }).show();
                    }

                    @Override
                    public void onFailed(String message) {
                        ProgressDialogUtils.dismiss();
                        Tools.showToast(message);
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (int i = 0; i < recyclerView.getChildCount(); i++) {
            View view = recyclerView.getChildAt(i);
            if (view != null) {
                UserSelectWidget targetView = view.findViewById(R.id.user_select_widget);
                if (targetView != null) {
                    targetView.onActivityResult(requestCode, resultCode, data);
                }
                ViewPortView viewPortView = view.findViewById(R.id.view_port);
                if (viewPortView != null) {
                    viewPortView.onActivityResult(requestCode, resultCode, data);
                }
                AttachmentSelectWidget attachWidget = view.findViewById(R.id.attach_select_widget);
                if (attachWidget != null) {
                    attachWidget.onActivityResult(requestCode, resultCode, data);
                }
            }
        }
        if (requestCode == 7002 && resultCode == Activity.RESULT_OK) {
            ArrayList<User> selectedUsers = (ArrayList<User>) data.getSerializableExtra(Keys.SELECTED_RESULTS);
            if (selectedUsers != null && selectedUsers.size() > 0) {
                asignFormTo(selectedUsers.get(0));
            }
        }
    }

    @Subscribe
    public void onReceiveEvent(SimpleEvent event) {
        if (event.getId() == 7001) {
            requestData();
        }
    }
}
